#include <iostream>
#include <websocketpp/server.hpp>
#include <websocketpp/config/asio_no_tls.hpp>

typedef websocketpp::server<websocketpp::config::asio> wsserver_t;

void http_handler(wsserver_t *srv, websocketpp::connection_hdl hdl)
{
    wsserver_t::connection_ptr conn = srv->get_con_from_hdl(hdl);
    std::cout << "Body:" << conn->get_request_body() << std::endl;
    websocketpp::http::parser::request req = conn->get_request();
    std::cout << "method: " << req.get_method() << std::endl;
    std::cout << "uri: " << req.get_uri() << std::endl;

    std::string body = "<html><body><h1>Hello World</h1></body></html>";
    conn->set_body(body);
    conn->append_header("Content-Type", "text/html");
    conn->set_status(websocketpp::http::status_code::ok);
}
void open_handler(wsserver_t *srv, websocketpp::connection_hdl hdl)
{
    std::cout << "websocket握手成功！！\n";
}
void close_handler(wsserver_t *srv, websocketpp::connection_hdl hdl)
{
    std::cout << "websocket连接断开！！\n";
}
void message_handler(wsserver_t *srv, websocketpp::connection_hdl hdl, wsserver_t::message_ptr msg)
{
    wsserver_t::connection_ptr conn = srv->get_con_from_hdl(hdl);
    std::cout << "wsmsg: " << msg->get_payload() << std::endl;
    std::string rsp = "client say: " + msg->get_payload();
    conn->send(rsp, websocketpp::frame::opcode::text);
}

int main()
{
    // 1.实例化server对象
    wsserver_t wsserver;
    // 2.设置日志等级
    wsserver.set_access_channels(websocketpp::log::alevel::none);
    // 3.初始化asio调度器
    wsserver.init_asio();
    wsserver.set_reuse_addr(true); // 设置地址复用
    // 4，设置回调函数
    wsserver.set_http_handler(bind(http_handler, &wsserver, std::placeholders::_1));
    wsserver.set_open_handler(bind(open_handler, &wsserver, std::placeholders::_1));
    wsserver.set_close_handler(bind(close_handler, &wsserver, std::placeholders::_1));
    wsserver.set_message_handler(bind(message_handler, &wsserver, std::placeholders::_1, std::placeholders::_2));
    // 5.设置监听端口
    wsserver.listen(8888);
    // 6.获取新连接
    wsserver.start_accept();
    // 7.启动服务器，执行服务
    wsserver.run();
    return 0;
}